<template>
  <div
    ref="editorContainer"
    class="monaco-editor-container"
    :style="{ height: `${height}px` }"
  ></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onBeforeUnmount, watch, ref, PropType } from 'vue'
import * as monaco from 'monaco-editor'
import { initializeMagicScript } from '@/components/MagicEditor/src/scripts/editor/magic-script'
import JavaClass from '@/components/MagicEditor/src/scripts/editor/java-class'

export default defineComponent({
  name: 'MonacoEditor',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    language: {
      type: String as PropType<
        | 'json'
        | 'javascript'
        | 'typescript'
        | 'html'
        | 'css'
        | 'markdown'
        | 'magicscript'
        | 'plaintext'
        | 'xml'
      >,
      default: 'json'
    },
    theme: {
      type: String,
      default: 'vs'
    },
    height: {
      type: Number,
      default: 300
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const editorContainer = ref<HTMLElement | null>(null)
    let editor: monaco.editor.IStandaloneCodeEditor | null = null
    self.MonacoEnvironment = {
      getWorker: function (workerId, label) {
        const workerMap = {
          json: new URL('monaco-editor/esm/vs/language/json/json.worker.js', import.meta.url),
          css: new URL('monaco-editor/esm/vs/language/css/css.worker.js', import.meta.url),
          html: new URL('monaco-editor/esm/vs/language/html/html.worker.js', import.meta.url),
          typescript: new URL(
            'monaco-editor/esm/vs/language/typescript/ts.worker.js',
            import.meta.url
          ),
          javascript: new URL(
            'monaco-editor/esm/vs/language/typescript/ts.worker.js',
            import.meta.url
          ),
          default: new URL('monaco-editor/esm/vs/editor/editor.worker.js', import.meta.url)
        }

        return new Worker(workerMap[label] || workerMap.default, { type: 'module' })
      }
    }

    onMounted(() => {

      Promise.all([JavaClass.initClasses(), JavaClass.initImportClass()])
        .then(e => {
           console.log('JavaClass init success')
        })

      debugger
      initializeMagicScript()
      if (editorContainer.value) {
        // 确保容器高度正确
        editorContainer.value.style.height = `${props.height}px`

        editor = monaco.editor.create(editorContainer.value, {
          value: props.modelValue,
          language: props.language,
          theme: props.theme,
          automaticLayout: true,
          minimap: { enabled: false },
          scrollBeyondLastLine: false,
          lineNumbers: 'on',
          scrollbar: {
            vertical: 'auto',
            horizontal: 'auto'
          }
        })

        // 监听编辑器内容变化并更新
        editor.onDidChangeModelContent(() => {
          const value = editor?.getValue() || ''
          if (value !== props.modelValue) {
            emit('update:modelValue', value)
          }
        })

        // 强制布局更新
        setTimeout(() => {
          if (editor) {
            editor.layout()
          }
        }, 100)
      }
    })

    // 监听属性变化更新编辑器
    watch(
      () => props.modelValue,
      (newValue) => {
        if (editor && newValue !== editor.getValue()) {
          editor.setValue(newValue)
        }
      }
    )

    watch(
      () => props.language,
      (newLang) => {
        if (editor) {
          monaco.editor.setModelLanguage(editor.getModel()!, newLang)
        }
      }
    )

    watch(
      () => props.height,
      (newHeight) => {
        if (editorContainer.value) {
          editorContainer.value.style.height = `${newHeight}px`
        }
        if (editor) {
          editor.layout()
        }
      }
    )

    onBeforeUnmount(() => {
      if (editor) {
        editor.dispose()
      }
    })

    return {
      editorContainer
    }
  }
})
</script>

<style scoped>
.monaco-editor-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden; /* 确保编辑器不溢出 */
}
</style>
